﻿using UnityEngine;
using System.Collections;

public class SteeringMove : MonoBehaviour,ISteeringGear {
	public Vector3 _steeringForce;
	Vector3 _targetsteeringForce;
	Vector3 _steeringSmoothDampSpeed;
	public float _steeringSpeed;
	float _lastZeroTime;
	public Vector3 SteeringForce{
		set{ 
			if (_targetsteeringForce != value) {
				_targetsteeringForce = value;
				if (_targetsteeringForce == Vector3.zero)
					_lastZeroTime = Time.time;
			}
		}
	}


	public Transform target;

	public float moveSpeed;
	public float turningSpeed;
	public float mindinstance;

	Transform cachedTransform;
	bool moveing;
	void Awake(){
		cachedTransform = transform;
	}
	void Update(){
		if (_steeringForce != _targetsteeringForce) {
			_steeringForce = Vector3.SmoothDamp (_steeringForce, _targetsteeringForce, ref _steeringSmoothDampSpeed, _steeringSpeed);
			if (_targetsteeringForce == Vector3.zero &&Time.time - _lastZeroTime >.5f) {
				_steeringForce = Vector3.zero;
			}
		}
		if (target == null)
			return;
		float dis = Vector3.Distance (target.position,cachedTransform.position);
		if (moveing) {
			cachedTransform.position += cachedTransform.forward*moveSpeed*Time.deltaTime;
			if (dis < mindinstance)
				moveing = false;
		} else {
			if (dis > mindinstance)
				moveing = true;
		}
		RotateTowards (target.position - cachedTransform.position);
	}

	void RotateTowards (Vector3 dir) {

		if (dir == Vector3.zero) return;
		if(_steeringForce!= Vector3.zero && moveing)
			dir = _steeringForce;
		Quaternion rot = cachedTransform.rotation;
		Quaternion toTarget = Quaternion.LookRotation(dir);

		rot = Quaternion.Slerp(rot, toTarget, turningSpeed*Time.deltaTime);
		Vector3 euler = rot.eulerAngles;
		euler.z = 0;
		euler.x = 0;
		rot = Quaternion.Euler(euler);

		cachedTransform.rotation = rot;
	}
}
